package com.ctshk.rpc.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SupplierStatus;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.cms.dto.BranchOfficeDTO;
import com.ctshk.rpc.cms.entity.BranchOffice;
import com.ctshk.rpc.cms.mapper.BranchOfficeMapper;
import com.ctshk.rpc.cms.req.BranchOfficeAddReq;
import com.ctshk.rpc.cms.req.BranchOfficeQueryReq;
import com.ctshk.rpc.cms.req.BranchOfficeUpdateReq;
import com.ctshk.rpc.cms.req.UpdateStatusReq;
import com.ctshk.rpc.cms.service.IBranchOfficeService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 分社表 服务实现类
 * </p>
 *
 * @author LiZhiming
 * @since 2021-04-23
 */
@DubboService
public class BranchOfficeServiceImpl extends ServiceImpl<BranchOfficeMapper, BranchOffice> implements IBranchOfficeService {

    @DubboReference
    private ISysUserService sysUserService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result insert(BranchOfficeAddReq req, TokenUser tu) {
        BranchOffice bo = EntityUtil.copy(req, BranchOffice.class);
        LocalDateTime now = LocalDateTime.now();
        Long id = IdWorker.getId();
        bo.setCreateId(tu.getId());
        bo.setGmtCreate(now);
        bo.setId(id);
        bo.setIsDeleted(IsDeletedCode.NO.getCode());
        int insert = baseMapper.insert(bo);
        if (insert > 0) {
            if (redisTemplate.hasKey(BaiDuApiServiceImpl.BRANCH_OFFICE_KEY)) {
                redisTemplate.delete(BaiDuApiServiceImpl.BRANCH_OFFICE_KEY);
            }
            return Result.success(id);
        }
        return Result.failed(SystemError.CMS_23000);
    }

    @Override
    public Result<BranchOfficeDTO> queryById(String branchOfficeId) {
        BranchOfficeDTO b = null;
        QueryWrapper<BranchOffice> qw = new QueryWrapper<>();
        qw.lambda().eq(BranchOffice::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(BranchOffice::getId, branchOfficeId);
        BranchOffice bo = baseMapper.selectOne(qw);
        if (bo != null) {
            b = EntityUtil.copy(bo, BranchOfficeDTO.class);
        }
        return Result.success(b);
    }

    @Override
    public PageResponse<BranchOfficeDTO> queryList(BranchOfficeQueryReq req) {
        Page<BranchOffice> page = new Page(req.getPageNo(), req.getPageSize());
        QueryWrapper<BranchOffice> qw = new QueryWrapper();
        qw.lambda().eq(BranchOffice::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(req.getName() != null, BranchOffice::getName, req.getName());
        Page<BranchOffice> boPage = baseMapper.selectPage(page, qw);
        if (CollectionUtils.isNotEmpty(boPage.getRecords())) {
            List<BranchOfficeDTO> boDTOS = EntityUtil.copyList(boPage.getRecords(), BranchOfficeDTO.class);
            //填充创建人名称
            Set<Long> ids = boDTOS.stream().map(e -> e.getCreateId()).collect(Collectors.toSet());
            List<UserDTO> users = sysUserService.getUsers(ids);
            Map<Long, String> us = new HashMap<>();
            users.stream().forEach(e -> us.put(e.getId(), e.getFullName()));
            boDTOS.stream().forEach(e -> e.setUserName(us.get(e.getCreateId())));
            return new PageResponse<>(boDTOS,
                    page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                    page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        }
        return new PageResponse<>(null,
                page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public PageResponse<BranchOfficeDTO> queryListAll(BranchOfficeQueryReq req) {
        Page<BranchOffice> page = new Page(req.getPageNo(), req.getPageSize());
        QueryWrapper<BranchOffice> qw = new QueryWrapper();
        qw.lambda().eq(BranchOffice::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(BranchOffice::getStatus, SupplierStatus.ENABLE.getCode());
        Page<BranchOffice> boPage = baseMapper.selectPage(page, qw);
        if (CollectionUtils.isNotEmpty(boPage.getRecords())) {
            List<BranchOfficeDTO> boDTOS = EntityUtil.copyList(boPage.getRecords(), BranchOfficeDTO.class);
            //填充创建人名称
            Set<Long> ids = boDTOS.stream().map(e -> e.getCreateId()).collect(Collectors.toSet());
            List<UserDTO> users = sysUserService.getUsers(ids);
            Map<Long, String> us = new HashMap<>();
            users.stream().forEach(e -> us.put(e.getId(), e.getFullName()));
            boDTOS.stream().forEach(e -> e.setUserName(us.get(e.getCreateId())));
            return new PageResponse<>(boDTOS,
                    page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                    page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        }
        return new PageResponse<>(null,
                page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public Result update(BranchOfficeUpdateReq req, TokenUser tu) {
        LocalDateTime now = LocalDateTime.now();
        BranchOffice copy = EntityUtil.copy(req, BranchOffice.class);
        copy.setModifiedId(tu.getId());
        copy.setGmtModified(now);
        int i = baseMapper.updateById(copy);
        if (i > 0) {
            if (redisTemplate.hasKey(BaiDuApiServiceImpl.BRANCH_OFFICE_KEY)) {
                redisTemplate.delete(BaiDuApiServiceImpl.BRANCH_OFFICE_KEY);
            }
            return Result.success(req.getId());
        }
        return Result.failed(SystemError.CMS_23002);
    }

    @Override
    public Result updateStatusById(UpdateStatusReq req) {
        int i = baseMapper.updateStatusById(req.getId(), req.getStatus());
        if (i > 0) {
            if (redisTemplate.hasKey(BaiDuApiServiceImpl.BRANCH_OFFICE_KEY)) {
                redisTemplate.delete(BaiDuApiServiceImpl.BRANCH_OFFICE_KEY);
            }
        }
        return Result.success(i);
    }
}
